using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;

using Microsoft.Extensions.Configuration;
using AutoMapper;
using Ant.EntityFrameworkCore.Model;
using Consul;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Ant.DbServiceInterface;
using Ant.DbService;
using Microsoft.AspNetCore.Authentication.Certificate;
using System.Net;
using System.Net.Sockets;

namespace Ant.Service.PersonnelManagement
{
    public class Startup
    {
        private IConfiguration _configuration;
        public Startup(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme)
                .AddCertificate()
                .AddCertificateCache()
                .AddCookie();

            services.AddCors(options => options.AddDefaultPolicy(
                policy => policy
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowAnyOrigin()
                // .AllowCredentials()

                ));

            // services.AddSession();
            // services.AddSingleton<IDistributedCache>(
            //     r => new RedisCache(new RedisCacheOptions()
            //     {
            //         Configuration = "127.0.0.1",
            //         InstanceName = "RedisServer"
            //     })
            // );

            //添加控制器依赖
            services.AddControllers();
            //配置HttpClient
            services.AddHttpClient();
            //配置数据库依赖
            services.AddDbContext<AntDB2Context>(optionsAction =>
            {
                optionsAction.UseSqlServer(_configuration["ConnectString"]);
            });
            services.AddTransient<IPersonneDataService, PersonneDataService>();
            services.AddTransient<IPayDataService, PayDataService>();
            services.AddTransient<IStoreDataService, StoreDataService>();
            //配置AutoMapper
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

            //注册JWT验证
            var key = System.Text.Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]);
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                    .AddJwtBearer(options =>
                    {
                        options.TokenValidationParameters = new TokenValidationParameters()
                        {
                            ValidateIssuer = true,
                            ValidIssuer = "localhost",
                            ValidateAudience = true,
                            ValidAudience = "localhost",
                            ValidateLifetime = true,

                            IssuerSigningKey = new SymmetricSecurityKey(key)
                        };
                    });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();
            // app.UseSession();
            app.UseAuthentication();
            //加入JWT中间件
            app.UseAuthentication();

            app.UseCors();

            //加入JWT中间件
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            /// <summary>
            /// 配置Consul服务发现
            /// </summary>
            string ip = _configuration["ip"];
            string consulIp = _configuration["ConsulServer"];
            int port = 0;
            try
            {
                var temp = _configuration["consul"];
                if (temp != "")
                {
                    consulIp = $"http://{temp}:8500/";
                }
            }
            catch (System.Exception)
            {
            }
            try
            {
                port = int.Parse(_configuration["port"]);
            }
            catch (System.Exception)
            {
                port = int.Parse(_configuration["defPort"]);
            }

            ConsulClient client = new ConsulClient(c =>
            {
                System.Console.WriteLine(consulIp);
                c.Address = new Uri(consulIp);
                c.Datacenter = "dc1";
            });
            string name = Dns.GetHostName();
            IPAddress[] ipadrlist = Dns.GetHostAddresses(name);
            foreach (var item in ipadrlist)
            {
                if (item.AddressFamily == AddressFamily.InterNetwork)
                    ip = item.ToString();
                    // System.Console.WriteLine(item.ToString());
            }
            var checkIp = $"http://{ip}:{port}/api/health/";
            System.Console.WriteLine(checkIp);
            client.Agent.ServiceRegister(new AgentServiceRegistration()
            {
                ID = "Ant" + Guid.NewGuid(),
                Name = "Ant",
                Address = ip,
                Port = port,
                Tags = new string[] { "test" },
                Check = new AgentServiceCheck()
                {
                    Interval = TimeSpan.FromSeconds(5),
                    HTTP = checkIp,
                    Timeout = TimeSpan.FromSeconds(5),
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(10)
                }

            });
        }
    }
}
